//
//  SXReadDetailViewController.m
//  ShiXun
//
//  Created by lanou on 15/10/30.
//  Copyright © 2015年 张琪. All rights reserved.
//

#import "SXReadDetailViewController.h"
#import "SXReadDetailListTableViewCell.h"
#import "SXRequestManager.h"
#import "SXReadRecommendDetailViewController.h"
#import "SXCollectionManager.h"

@interface SXReadDetailViewController () <UITableViewDataSource, UITableViewDelegate>

@end

@implementation SXReadDetailViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
}

- (UITableView *)mainTableView
{
    if (!_mainTableView) {
        _mainTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenHeight - 64)];
        _mainTableView.delegate = self;
        _mainTableView.dataSource = self;
        [_mainTableView registerClass:[SXReadDetailListTableViewCell class] forCellReuseIdentifier:@"SXReadDetailListTableViewCell"];
    }
    return _mainTableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationController.navigationBar.hidden = NO;
    
    self.navigationItem.title = _titleString;
    
    BOOL isSubscibe = [SXCollectionManager checkCollectionWithTableName:@"readSubscibe" urlID:_tid];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"SX-yuedudingyuejia"] imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)] style:(UIBarButtonItemStyleDone) target:self action:@selector(subscibe:)];
    self.navigationItem.rightBarButtonItem.tag = 1100;
    if (isSubscibe) {
        self.navigationItem.rightBarButtonItem.image = [[UIImage imageNamed:@"SX-yuedudingyuejian"] imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)];
        self.navigationItem.rightBarButtonItem.tag = 1101;
    }
    
    _start = 0;
    _limit = 20;
    
    [self requestData];
}

- (void)requestData
{
    NSString *urlString = [kReadDetailListURLString stringByAppendingFormat:@"%@/%ld-%ld.html", _tid, _start, _limit];
    
    [SXRequestManager requestWithType:GET urlString:urlString parDic:nil finish:^(NSData *data) {

        [self analysisData:data];
        
    } error:^(NSError *error) {
        NSLog(@"推荐阅读界面数据请求失败");
        [self removeLoadingView];
    }];
}

// 点击收藏按钮
- (void)subscibe:(UIBarButtonItem *)item
{
    BOOL isSubscibe;
    NSString *titleStr;
    if (item.tag == 1100) {
        item.image = [[UIImage imageNamed:@"SX-yuedudingyuejian"] imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)];
        item.tag = 1101;
        isSubscibe = YES;
        titleStr = @"订阅阅读成功";
    }
    else
    {
        item.image = [[UIImage imageNamed:@"SX-yuedudingyuejia"] imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)];
        item.tag = 1100;
        isSubscibe = NO;
        titleStr = @"取消订阅成功";
    }
    [SXCollectionManager collectionDataWithTableName:@"readSubscibe" title:_titleString urlID:_tid isCollection:isSubscibe finish:^(BOOL isSuccessed) {
        if (isSuccessed) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"changeSubscibe" object:nil];
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:titleStr delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
            [alertView show];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [alertView dismissWithClickedButtonIndex:0 animated:NO];
            });
        }
    }];
}

// 数据解析
- (void)analysisData:(NSData *)data
{
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers) error:nil];
    NSArray *array = dict[_tid];
    if (_start == 0) {
        [self.dataSourceArray removeAllObjects];
    }
    for (NSDictionary *dic in array) {
        SXReadModel *model = [[SXReadModel alloc] init];
        [model setValuesForKeysWithDictionary:dic];
        [self.dataSourceArray addObject:model];
    }
    [self.mainTableView reloadData];
    [self removeLoadingView];
}

// cell个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSourceArray.count;
}

// cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SXReadModel *model = self.dataSourceArray[indexPath.row];
    SXReadDetailListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SXReadDetailListTableViewCell" forIndexPath:indexPath];
    cell.congfigureModel = model;
    return cell;
}

// row高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SXReadModel *model = self.dataSourceArray[indexPath.row];
    return [SXReadDetailListTableViewCell heightForCellWithModel:model];
}

// 点击cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    SXReadModel *model = self.dataSourceArray[indexPath.row];
    SXReadRecommendDetailViewController *detailVC = [[SXReadRecommendDetailViewController alloc] init];
    detailVC.docid = model.docid;
    UIBarButtonItem *temporaryBarButtonItem = [[UIBarButtonItem alloc] init];
    temporaryBarButtonItem.title =@"";
    self.navigationItem.backBarButtonItem = temporaryBarButtonItem;
    [self.navigationController pushViewController:detailVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
